/**
 * Created by xiey on 2016/3/24.
 */
as.constant('LOAD_STATE', {
    LOADING: 1,
    SUCCESS: 2,
    ERROR  : 3
}).directive('aStore', ['$http', '$timeout', 'LOAD_STATE', function ($http, $timeout, LOAD_STATE) {
    return {
        restrict: 'E',
        require : 'ngModel',
        scope   : {
            api        : '@',
            params     : '<',
            stateChange: '&',
            state      : '=' // [1.loading 2.success 3.error]
        },
        link    : function (scope, el, attr, ngModel) {
            if (!scope.api) {
                return;
            }
            var changeLoadState = function (state) {
                scope.state = state;
                $timeout(function () {
                    scope.stateChange();
                });
            };
            var requestData = function () {
                changeLoadState(LOAD_STATE.LOADING);
                $http.get(scope.api, {
                    params: scope.params
                }).then(function (result) {
                    ngModel.$setViewValue(result);
                    changeLoadState(LOAD_STATE.SUCCESS);
                }, function () {
                    ngModel.$setViewValue(null);
                    changeLoadState(LOAD_STATE.ERROR);
                }).finally(function () {
                    scope.loading = false;
                });
            };
            scope.$watch('params', function () {
                requestData();
            }, true);
        }
    };
}]);